package com.heima.search.service.impl;


import com.alibaba.fastjson.JSON;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.search.dtos.UserSearchDto;
import com.heima.model.user.pojos.ApUser;
import com.heima.search.service.ApUserSearchService;
import com.heima.search.service.ArticleSearchService;
import com.heima.utils.common.AppThreadLocalUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.common.text.Text;
import org.elasticsearch.index.query.BoolQueryBuilder;
import org.elasticsearch.index.query.Operator;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.SearchHits;
import org.elasticsearch.search.builder.SearchSourceBuilder;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightBuilder;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightField;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

@Slf4j
@Service
@Transactional
public class ArticleSearchImpl implements ArticleSearchService {


    @Autowired
    private RestHighLevelClient client;

    //注入搜索记录保存服务
    @Autowired
    private ApUserSearchService apUserSearchService;

    //文章搜索实现
    @Override
    public ResponseResult search(UserSearchDto dto) throws IOException {
        //2.创建SearchRequest对象--->索引库名app_info_article
        SearchRequest searchRequest = new SearchRequest("app_info_article");
        //组装搜索 查询判断条件
        SearchSourceBuilder sourceBuilder = new SearchSourceBuilder();

        BoolQueryBuilder boolQueryBuilder = QueryBuilders.boolQuery();
        //请求的关键字非空判断
        if (StringUtils.isEmpty(dto.getSearchWords())) {
            //如果是空就查询所有
            boolQueryBuilder.must(QueryBuilders.matchAllQuery());

        }else {
            //不是 -就按照关键字分词之后在查询  ->标题和内容
            boolQueryBuilder.must(QueryBuilders.queryStringQuery(dto.getSearchWords())
                    .field("title")
                    .field("content")
                    .defaultOperator(Operator.OR));//分词之后的词条关系
            //从线程工具类中去获取用户信息
            ApUser user = AppThreadLocalUtil.getUser();
            if (user != null && dto.getFromIndex() == 0) {
                //异步保存 用户搜索记录
                apUserSearchService.insert(dto.getSearchWords(), user.getId());
            }

        }
        //设置文章的时间范围 filter是条件过滤器,field是设置具体的搜索那个字段
        //gt,这里写小于是因为数据库中的数据创建时间都是以前的  所以写的小于,正常一般都写大于
        boolQueryBuilder.filter(QueryBuilders.rangeQuery("publishTime").lt(dto.getMinBehotTime()));

        sourceBuilder.query(boolQueryBuilder);

        //设置分页
        //分页设置-1*dto.getPageSize(),那个分页公式
//        sourceBuilder.from((dto.getPageNum() -1) * dto.getPageSize());
        sourceBuilder.from(dto.getPageNum() * dto.getPageSize());//这里因为这个前端传过来的请求页数是零
        // 这里就不能减一按照第0个索引来搜了  一般前端传的都是1,代表第一页,我们搜索是按所以0开始 所以要设置减一
        sourceBuilder.size(dto.getPageSize());

        //高亮展示
        searchRequest.source().highlighter(new HighlightBuilder()
                .field("title")
                .preTags("<font style='color: red; font-size: inherit;'>")
                .postTags("</font>"));

        searchRequest.source(sourceBuilder);
        SearchResponse searchResponse = client.search(searchRequest, RequestOptions.DEFAULT);

        //解析结果
        SearchHits hits = searchResponse.getHits();
        long total = hits.getTotalHits().value;//总记录数据 --手机是用上拉下滑来进行更多内容的展示所以这个总记录数可以不要
        SearchHit[] searchHits = hits.getHits();//获取匹配的数据

        List<Map> list = null;
        //然后遍历获取 建个集合来装
        if ( null != searchHits && searchHits.length>0 ) {
            //集合的长度就是这个记录的长度
            list =new ArrayList<>(searchHits.length);
            for (SearchHit searchHit : searchHits) {
                String json = searchHit.getSourceAsString();


                Map map = JSON.parseObject(json, Map.class);


                //解析高亮数据 将每个遍历出来的数据设置高亮
                Map<String, HighlightField> highlightFieldMap = searchHit.getHighlightFields();
                if (null != highlightFieldMap && highlightFieldMap.size() > 0) {
                    //获取标题词条进行高亮设置
                    HighlightField highlightField = highlightFieldMap.get("title");
                    Text[] fragments = highlightField.getFragments();

                    map.put("h_title",StringUtils.join(fragments));
                }else {
                    map.put("h_title",map.get("title"));
                }


                list.add(map);
            }
        }
        //返回结果
        return ResponseResult.okResult(list);
    }
}
